package com.jianjun.framework.security.service;


import cn.hutool.core.collection.CollectionUtil;
import com.jfinal.aop.Inject;
import com.jianjun.common.constant.Constants;
import com.jianjun.common.constant.UserConstants;
import com.jianjun.project.common.model.SysRole;
import com.jianjun.project.common.model.SysUser;
import com.jianjun.project.system.menu.SysMenuService;
import com.jianjun.project.system.role.SysRoleService;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 用户权限处理
 *
 * @author source
 */
public class SysPermissionService {
    @Inject
    SysRoleService roleService;
    @Inject
    SysMenuService menuService;

    /**
     * 获取角色数据权限
     *
     * @param user 用户信息
     * @return 角色权限信息
     */
    public Set<String> getRolePermission(SysUser user) {
        Set<String> roles = new HashSet<>();
        // 管理员拥有所有权限
        if (user.isAdmin()) {
            roles.add("admin");
        } else {
            roles.addAll(roleService.selectRolePermissionByUserId(user.getUserId()));
        }
        return roles;
    }

    /**
     * 获取菜单数据权限
     *
     * @param user 用户信息
     * @return 菜单权限信息
     */
    public Set<String> getMenuPermission(SysUser user) {
        Set<String> perms = new HashSet<>();
        // 管理员拥有所有权限
        if (user.isAdmin()) {
            perms.add(Constants.ALL_PERMISSION);
        } else {
            List<SysRole> roles = user.getRoles();
            if (!CollectionUtil.isEmpty(roles)) {
                // 设置permissions属性，以便数据权限匹配权限
                for (SysRole role : roles) {
                    if (UserConstants.ROLE_NORMAL.equals(role.getStatus())) {
                        Set<String> rolePerms = menuService.selectMenuPermsByRoleId(role.getRoleId());
                        role.setPermissions(rolePerms);
                        perms.addAll(rolePerms);
                    }
                }
            } else {
                perms.addAll(menuService.selectMenuPermsByUserId(user.getUserId()));
            }
        }
        return perms;
    }
}
